/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */
import React, {useState, useEffect, useMemo} from 'react';
import {
  TabController,
  View,
  Colors,
  Button,
  Text,
  Checkbox,
  SegmentedControl,
  Image,
  TouchableOpacity,
} from 'react-native-ui-lib';
import {ActivityIndicator} from 'react-native';
import {connect} from 'react-redux';
import Input from '@/components/Input';
import {get, update} from '@/utils/request';
import {useRequest} from 'ahooks';
import AuditList from '@/components/AuditList';
import ProjectIcon from '@/components/ProjectIcon';
import Mheader from '@/components/Mheader';

const conf = {
  0: {
    key: '0',
    text: '待审批',
  },
  1: {
    key: '1',
    text: '已审批',
  },
};

function Audit({navigation, appTheme, curProject}) {
  const Prefix = global.file;

  const [index, setIndex] = useState(0);
  const [rerender, setRerender] = useState(true);
  const [checkedList, setCheckedList] = useState([]);

  //接口
  const {data, refreshAsync} = useRequest(
    async () => {
      let res = await get('/itemWorkTime/pm', {});
      return res?.data?.dataList;
    },
    {
      refreshDeps: [],
    },
  );

  const todo = useMemo(() => {
    return (
      data?.filter(it => it.status === 2)?.[0] ?? {
        status: 2,
        statusName: '待审核',
        list: [],
      }
    );
  }, [data]);

  const done = useMemo(() => {
    return (
      data?.filter(it => it.status === 4)?.[0] ?? {
        status: 4,
        statusName: '通过',
        list: [],
      }
    );
  }, [data]);

  const {runAsync, loading} = useRequest(update, {
    manual: true,
    onSuccess: res => {
      if (res.code === 0) {
        navigation.goBack();
      }
    },
  });

  //   const extraprops = {
  //     refreshAsync,
  //     loading,
  //   };

  useEffect(() => {
    setRerender(false);
    setTimeout(() => {
      setRerender(true);
    }, 10);
  }, [appTheme]);

  const plainOptions = todo?.list ?? [];
  const checkAll = plainOptions?.length === checkedList?.length;

  // 全选/反选
  const onCheckAllChange = checked => {
    setCheckedList(
      checked
        ? plainOptions?.map(it => {
            return {
              id: it.id,
              refuse:
                checkedList?.filter(item => it.id === item.id)?.[0]?.refuse ??
                null,
            };
          })
        : [],
    );
  };

  return (
    <View
      flex-1
      style={{
        backgroundColor: Colors.backgroundColor,
      }}>
      <Mheader
        title={'日报审批'}
        extraContent={
          index === 0 && (
            <Button
              disabled={loading}
              label="提交"
              size="xsmall"
              backgroundColor={Colors.primaryColor}
              style={{borderRadius: 6, width: 56}}
              iconSource={() => {
                return loading ? (
                  <ActivityIndicator color={Colors.primaryColor} />
                ) : null;
              }}
              onPress={async () => {
                const submits = checkedList.map(it => {
                  return {
                    id: it?.id,
                    status: it?.refuse ? 3 : 4,
                    refuse: it.refuse,
                  };
                });
                await runAsync('/itemWorkTime', submits);
              }}
            />
          )
        }
      />
      <View flex-1 style={{marginTop: -10}} paddingB-10>
        <TabController
          items={Object.entries(conf)?.map(([key, value]) => ({
            label:
              value.text +
              ' ' +
              (key === '0' ? todo?.list?.length : done?.list?.length),
          }))}
          asCarousel={true}
          onChangeIndex={setIndex}>
          {rerender && (
            <TabController.TabBar
              enableShadows
              spreadItems
              labelColor={Colors.colorTextBase}
              selectedLabelColor={Colors.primaryColor}
              indicatorStyle={{
                backgroundColor: Colors.primaryColor,
              }}
              backgroundColor={Colors.backgroundColor}
            />
          )}
          <TabController.PageCarousel flex-1>
            <TabController.TabPage index={0}>
              <View flex-1>
                <View padding-12 paddingH-24 paddingB-6 row spread>
                  <Checkbox
                    value={checkAll}
                    onValueChange={onCheckAllChange}
                    color={Colors.primaryColor}
                    labelStyle={{marginLeft: 8, color: Colors.primaryColor}}
                    label="全选"
                  />
                  <Text>选中 {checkedList?.length} 项</Text>
                </View>
                <AuditList
                  appTheme={appTheme}
                  data={todo?.list ?? []}
                  checkedList={checkedList}
                  setCheckedList={setCheckedList}
                />
              </View>
            </TabController.TabPage>
            <TabController.TabPage index={1} lazy>
              <AuditList
                appTheme={appTheme}
                data={done?.list ?? []}
                checkedList={checkedList}
                setCheckedList={setCheckedList}
                done={true}
              />
            </TabController.TabPage>
          </TabController.PageCarousel>
        </TabController>
      </View>
    </View>
  );
}
const mapStateToProps = state => {
  return {
    appTheme: state.appTheme,
    curProject: state.curProject,
  };
};

export default connect(mapStateToProps)(Audit);
